#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "user_io.h"
#include "user_threads.h"
//#include "common.h"

int uthread_open(const char* filename, int flags) {
	return open(filename, flags | O_NONBLOCK);
}

int uthread_pipe(int filedes[2]) {
	int ret = pipe(filedes);
	if (ret < 0) {
		return ret;
	}
	fcntl(filedes[0],F_SETFL, O_NONBLOCK);
	fcntl(filedes[1],F_SETFL, O_NONBLOCK);
	return ret;
}

int uthread_read(int fd, void* buf, size_t count) {
	int retval = read(fd,buf,count);
	while (retval == -1 && errno == EAGAIN) {
		uthread_yield();
		retval = read(fd,buf,count);
	}
	return retval;
}

int uthread_write(int fd, const void* buf, size_t count) {
	int retval = write(fd,buf,count);
	while (retval == -1 && errno == EAGAIN) {
		uthread_yield();
		retval = write(fd,buf,count);
	}
	return retval;
}
